import 'dart:async';

import 'package:fate_blind_box/theme/theme_color.dart';
import 'package:fate_blind_box/utils/common_widget.dart';
import 'package:fate_blind_box/utils/page.dart';
import 'package:flutter/material.dart';

import '../../network/Api.dart';
import '../../network/http_config.dart';
import '../../utils/loading.dart';
import '../../utils/provider.dart';
import '../../utils/snack_bar.dart';

class passLoginUI extends StatelessWidget {
  const passLoginUI({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return AppWidget.navTitleBar(
      bgColor: Colors.white,
      childWidget: const SingleChildScrollView(
        child: _passLoginPage(),
      ),
    );
  }
}

class _passLoginPage extends StatefulWidget {
  const _passLoginPage({Key? key}) : super(key: key);

  @override
  State createState() {
    return _passLoginState();
  }
}

class _passLoginState extends State<_passLoginPage> {
  var _loginBtnSelector = [0xFFF5F6F6, 0xFF222222];
  final _loginBtnEnable = [0xFFFB6D99, 0xFFFFFFFF];
  final _loginBtnUnable = [0xFFF5F6F6, 0xFF222222];
  final TextEditingController _mobController = TextEditingController();
  final TextEditingController _codeController = TextEditingController();
  final TextEditingController _passController = TextEditingController();
  final TextEditingController _conPassController = TextEditingController();
  var check = false;
  bool _isObscure = true;
  Color _eyeColor = Colors.grey;
  bool _isObscure1 = true;
  Color _eyeColor1 = Colors.grey;

  @override
  void initState() {
    super.initState();
  }

  Timer? _timer;
  int _curTime = 0;

  _startCountdownTimer() {
    _curTime = 60;
    _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      setState(() {
        _curTime--;
      });
      if (_curTime <= 0) {
        _timer?.cancel();
      }
    });
  }

  String _smsSig = '';

  _sendVerifyCode() {
    if (_mobController.text.length < 11) {
      toast("请输入手机号");
      return false;
    }
    loading(() async {
      final res = await Api.getInstance().loginSendCode(_mobController.text);
      print(res);
      print(_mobController.text);
      if (res['code'] == 0) {
        if (res['data'] != null && res['data']['sig'] != null) {
          _smsSig = res['data']['sig'];
          _startCountdownTimer();
        }
      } else {
        ThemeSnackBar.show(context, res['msg']);
      }
    });
  }

  _modifyPass() {
    if (!_verify(true)) {
      return;
    }
    loading(() async {
      final res = await Api.getInstance().modfyPass(
          _mobController.text,
          _codeController.text,
          _smsSig,
          _passController.text,
          _conPassController.text);
      if (res['code'] == 0) {
        final data = res['data'];
        Provider.memberId = data['memberId'];
        Provider.memberInfo = data;
        HttpConfig.token = data['token'];
        await Provider.cache("memberId", Provider.memberId);
        await Provider.cache("token", HttpConfig.token);

        ThemeSnackBar.show(context, res['msg']);

        //修改密码成功，回到登录页面
        Provider.remove('token');
        Navigate.toLogin();
      }
      ThemeSnackBar.show(context, res['msg']);
    });
  }

  bool _verify(bool sendCode) {
    if (_mobController.text.length < 11) {
      toast("请输入手机号");
      return false;
    }
    if (_codeController.text.isEmpty) {
      toast("请输入验证码");
      return false;
    }
    if (_passController.text.isEmpty) {
      toast("请输入密码");
      return false;
    }

    if (_conPassController.text.isEmpty) {
      toast("请输入确认密码");
      return false;
    }
    return true;
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      color: Colors.white,
      child: Column(
        children: [
          //图片
          Container(
            margin: const EdgeInsets.only(top: 0.0),
            child: const Center(
              child: Image(
                width: 96,
                height: 96,
                image: AssetImage("images/new_logo.png"),
              ),
            ),
          ),
          // 标题
          const Center(
            child: Text(
              "都肆商圈",
              style: TextStyle(fontSize: 16, color: Color(0xFF2F2F2F)),
            ),
          ),
          //手机号
          Container(
            margin: const EdgeInsets.fromLTRB(40, 48, 40, 0),
            height: 45,
            color: const Color(0xFFF6F8FA),
            child: TextField(
              controller: _mobController,
              maxLength: 11,
              keyboardType: TextInputType.phone,
              cursorColor: const Color(0xFFFB6D99),
              style: const TextStyle(fontSize: 12, color: Color(0xFF222222)),
              decoration: InputDecoration(
                hintText: "请输入您的手机号",
                counterText: "",
                border: InputBorder.none,
                hintStyle: const TextStyle(color: Color(0xFF999999)),
                fillColor: const Color(0xffF1F3FB),
                filled: true,
                enabledBorder: const OutlineInputBorder(
                  /*边角*/
                  borderRadius: BorderRadius.all(
                    Radius.circular(5), //边角为30
                  ),
                  borderSide: BorderSide(
                    color: Colors.white54, //边线颜色为黄色
                    width: 1, //边线宽度为2
                  ),
                ),
                focusedBorder: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(5),
                  borderSide: const BorderSide(
                    color: Colors.white54, //边框颜色为绿色
                    width: 1, //宽度为5
                  ),
                ),
                contentPadding:
                    const EdgeInsets.only(top: 0, bottom: 0, left: 10),
              ),
              onChanged: (e) {
                setState(() {
                  _loginBtnSelector =
                      _mobController.text.length >= 6 && e.length >= 11
                          ? _loginBtnEnable
                          : _loginBtnUnable;
                });
              },
            ),
          ),
          //验证码
          Container(
              height: 45,
              margin: const EdgeInsets.fromLTRB(40, 12, 40, 0),
              // padding: const EdgeInsets.symmetric(horizontal: 12),
              // margin: const EdgeInsets.symmetric(vertical: 12, horizontal: 14),
              decoration: ShapeDecoration(
                  shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(5)),
                  color: const Color(0xffF1F3FB)),
              alignment: Alignment.centerLeft,
              child: Row(
                children: [
                  Expanded(
                    child: TextField(
                      controller: _codeController,
                      keyboardType: TextInputType.phone,
                      maxLength: 11,
                      maxLines: 1,
                      style:
                          TextStyle(fontSize: 12, color: ThemeColor.textColor),
                      decoration: const InputDecoration(
                        hintText: "请输入验证码",
                        border: InputBorder.none,
                        hintStyle: TextStyle(color: Color(0xFF999999)),
                        counterText: '',
                        fillColor: Color(0xffF1F3FB),
                        filled: true,
                      ),
                    ),
                  ),
                  Container(
                      width: 102,
                      height: 30,
                      // color: const Color(0xFF7F69D9),
                      decoration: BoxDecoration(
                        // border: Border.all(color: const Color(0xFF2C7FF8)),
                        borderRadius: BorderRadius.circular(15),
                        color: ThemeColor.colorCF8F23,
                      ),
                      alignment: Alignment.center,
                      child: GestureDetector(
                        onTap: () {
                          _sendVerifyCode();
                        },
                        child: Text(
                          _curTime > 0 ? "$_curTime秒后重新获取" : "获取验证码",
                          style: const TextStyle(
                              color: Colors.white, fontSize: 12),
                        ),
                      ))
                ],
              )),
          //密码
          Container(
            margin: const EdgeInsets.fromLTRB(40, 12, 40, 0),
            height: 45,
            child: TextField(
              controller: _passController,
              maxLength: 16,
              obscureText: _isObscure,
              keyboardType: TextInputType.text,
              cursorColor: ThemeColor.mainColor,
              style: TextStyle(fontSize: 12, color: ThemeColor.textColor),
              decoration: InputDecoration(
                hintText: "请输入6-18位新密码（数字/字母/字符)",
                counterText: "",
                border: InputBorder.none,
                hintStyle: TextStyle(color: ThemeColor.textColorSecond),
                fillColor: const Color(0xffF1F3FB),
                filled: true,
                enabledBorder: const OutlineInputBorder(
                  /*边角*/
                  borderRadius: BorderRadius.all(
                    Radius.circular(5), //边角为30
                  ),
                  borderSide: BorderSide(
                    color: Colors.white54, //边线颜色为黄色
                    width: 1, //边线宽度为2
                  ),
                ),
                focusedBorder: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(5),
                  borderSide: const BorderSide(
                    color: Colors.white54, //边框颜色为绿色
                    width: 1, //宽度为5
                  ),
                ),
                contentPadding:
                    const EdgeInsets.only(top: 0, bottom: 0, left: 10),
                suffixIcon: IconButton(
                  icon: Icon(
                    _isObscure ? Icons.visibility_off : Icons.visibility,
                    color: _eyeColor,
                  ),
                  onPressed: () {
                    setState(() {
                      _isObscure = !_isObscure;

                      _eyeColor = (_isObscure
                          ? Colors.grey
                          : Theme.of(context).iconTheme.color)!;
                    });
                  },
                ),

                // focusedBorder: const UnderlineInputBorder(
                //     borderSide: BorderSide(color: Color(0xFFEBEBEB))
                // ),
                // enabledBorder: const UnderlineInputBorder(
                //     borderSide: BorderSide(color: Color(0xFFEBEBEB))
                // )
              ),
            ),
          ),
          //新密码
          Container(
            margin: const EdgeInsets.fromLTRB(40, 12, 40, 0),
            height: 45,
            child: TextField(
              controller: _conPassController,
              maxLength: 16,
              obscureText: _isObscure1,
              keyboardType: TextInputType.text,
              cursorColor: ThemeColor.mainColor,
              style: TextStyle(fontSize: 12, color: ThemeColor.textColor),
              decoration: InputDecoration(
                hintText: "确认新密码",
                counterText: "",
                border: InputBorder.none,
                hintStyle: TextStyle(color: ThemeColor.textColorSecond),
                fillColor: const Color(0xffF1F3FB),
                filled: true,
                enabledBorder: const OutlineInputBorder(
                  /*边角*/
                  borderRadius: BorderRadius.all(
                    Radius.circular(5), //边角为30
                  ),
                  borderSide: BorderSide(
                    color: Colors.white54, //边线颜色为黄色
                    width: 1, //边线宽度为2
                  ),
                ),
                focusedBorder: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(5),
                  borderSide: const BorderSide(
                    color: Colors.white54, //边框颜色为绿色
                    width: 1, //宽度为5
                  ),
                ),
                contentPadding:
                    const EdgeInsets.only(top: 0, bottom: 0, left: 10),
                suffixIcon: IconButton(
                  icon: Icon(
                    _isObscure1 ? Icons.visibility_off : Icons.visibility,
                    color: _eyeColor1,
                  ),
                  onPressed: () {
                    setState(() {
                      _isObscure1 = !_isObscure1;

                      _eyeColor1 = (_isObscure1
                          ? Colors.grey
                          : Theme.of(context).iconTheme.color)!;
                    });
                  },
                ),

                // focusedBorder: const UnderlineInputBorder(
                //     borderSide: BorderSide(color: Color(0xFFEBEBEB))
                // ),
                // enabledBorder: const UnderlineInputBorder(
                //     borderSide: BorderSide(color: Color(0xFFEBEBEB))
                // )
              ),
            ),
          ),
          //确认
          GestureDetector(
            child: Container(
                margin: const EdgeInsets.fromLTRB(40, 30, 40, 0),
                height: 45,
                decoration: ShapeDecoration(
                  shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(22.5)),
                  color: ThemeColor.colorCF8F23,
                ),
                width: double.maxFinite,
                child: const Center(
                  child: Text(
                    "确定",
                    style: TextStyle(color: Colors.white, fontSize: 15),
                  ),
                )),
            onTap: () {
              _modifyPass();
            },
          ),
          Container(
            margin: const EdgeInsets.only(top: 14),
            child: Center(
                child: Text.rich(TextSpan(children: [
              const TextSpan(
                  text: "本操作将会重置您的登录密码，",
                  style: TextStyle(color: Color(0xFFCECECE), fontSize: 10)),
              TextSpan(
                text: "请牢记您的新密码",
                style: TextStyle(color: ThemeColor.colorCF8F23, fontSize: 10),
              ),
            ]))),
          ),
        ],
      ),
    );
  }
}
